package com.simple.util.base.extend.update;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @program: simple_tools
 * @description: 用于常用更新逻辑
 * @author: ChenWenLong
 * @create: 2019-10-17 14:17
 **/
public class UpdateUtil {

    //常见字段
    private static final String FIELD_NAME_ID = "id";
    public static final String FIELD_NAME_SORT ="sort";
    public static final String FIELD_NAME_UPDATE_TIME ="updateTime";

    //更新集合名称
    public static final String UPDATE_LIST_NAME ="updateList";
    public static final String DELETE_LIST_NAME ="deleteList";
    public static final String INSERT_LIST_NAME ="insertList";

    /**
     * 功能描述:
     *  1.应用场景
     *      1.1 编辑时新增
     *      1.2 编辑时删除
     *      1.3 编辑时改变内容不改变数量
     *  2.返回参数
     *       2.1 根据<>UPDATE_LIST_NAME</>获取需要更新的集合
     *       2.2 根据<>DELETE_LIST_NAME</>获取需要删除的集合
     *       2.3 根据<>INSERT_LIST_NAME</>获取需要新增的集合
     *
     * @params : [srcList, destList]
     * @return : java.util.Map<java.lang.String,java.util.List<org.apache.poi.ss.formula.functions.T>>
     * @author : cwl
     * @date : 2019/7/2 17:01
     */
    public static <T> Map<String,List<T>> update(List<T> srcList, List<T> destList, Long lastId) throws Exception {
        Map<String,List<T>> resultMap = new HashMap<>();
        List<T> updateList = new ArrayList<>();
        List<T> deleteList = new ArrayList<>();
        List<T> insertList = new ArrayList<>();

        //如果原有为空 现有不为空 则全部为新增
        if(isEmpty(srcList) && !isEmpty(destList)){
            for (T t : destList) {
                setIdfield(t);
            }
            resultMap.put(INSERT_LIST_NAME,destList);
            return resultMap;
        }
        //如果现有全部为空 原有不为空 则全部为删除
        if(!isEmpty(srcList) && isEmpty(destList)){
            resultMap.put(DELETE_LIST_NAME,srcList);
            return resultMap;
        }

        //数据准备
        Map<String, Integer> sortAndIdMap = setId(destList,lastId);
        List<String> srcIdList = getIdList(srcList);
        List<String> destIdList = getIdList(destList);
        Map<String, T> srcPOMap = getPOMap(srcList);
        Map<String, T> destPOMap = getPOMap(destList);

        List<String> deleteIdList = new ArrayList<>(srcIdList);
        List<String> insertIdList = new ArrayList<>(srcIdList);

        //1.原有与现有取交集,则更新
        srcIdList.retainAll(destIdList);
        for (String id : srcIdList) {
            T src = srcPOMap.get(id);
            T dest = destPOMap.get(id);
            Integer integer = sortAndIdMap.get(id);
            //TODO 此处建议引入common.lang3中的BeanUtils去进行拷贝操作
            //copyProperties(dest,src);
            updateSortAndTime(integer,src);
            updateList.add(src);
        }
        resultMap.put(UPDATE_LIST_NAME,updateList);

        //2.原有与现有取差集,则删除
        deleteIdList.removeAll(destIdList);
        for (String delId : deleteIdList) {
            if(srcPOMap.containsKey(delId)){
                T t = srcPOMap.get(delId);
                deleteList.add(t);
            }
        }
        resultMap.put(DELETE_LIST_NAME,deleteList);

        //3.现有与原有取差集,则新增
        destIdList.removeAll(insertIdList);
        for (String insertId : destIdList) {
            if(destPOMap.containsKey(insertId)){
                T t = destPOMap.get(insertId);
                insertList.add(t);
            }
        }
        resultMap.put(INSERT_LIST_NAME,insertList);
        return resultMap;
    }


    /**
     * 功能描述:
     * 〈更新该对象的排序信息,当前端没有传输sort字段时使用.〉
     *
     * @params : [src, dest]
     * @return : void
     * @author : cwl
     * @date : 2019/7/2 10:44
     */
    private static <T> void updateSortAndTime(Integer sort, T src)throws IllegalAccessException{
        Date date = new Date();
        Class<?> srcClass = src.getClass();
        Field sortField;
        Field updateTime;
        try {
            sortField = srcClass.getDeclaredField(FIELD_NAME_SORT);
            sortField.setAccessible(true);
            sortField.set(src,sort);
        } catch (NoSuchFieldException e) {
            //如果没有排序字段,则继续看看有没有更新时间
        }

        try {
            updateTime = srcClass.getDeclaredField(FIELD_NAME_UPDATE_TIME);
            updateTime.setAccessible(true);
            updateTime.set(src,date);
        }catch (NoSuchFieldException e) {
            //如果没有更新时间,则结束该方法
            return;
        }
    }

    /**
     * 功能描述:
     * 〈判断List是否为空〉
     *
     * @params : [judgeList]
     * @return : boolean
     * @author : cwl
     * @date : 2019/10/17 14:25
     */
    public static boolean isEmpty(List<?> judgeList){
        if(Collections.EMPTY_LIST == judgeList || null == judgeList){
            return true;
        }
        return false;
    }

    /**
     * 功能描述:
     * 〈判断对象是否为空〉
     *
     * @params : [o]
     * @return : boolean
     * @author : cwl
     * @date : 2019/10/17 14:30
     */
    public static boolean isEmpty(Object o){
        return null == o;
    }

    /**
     * 功能描述:
     * 〈根据反射设置ID的值〉
     *
     * @params : [src]
     * @return : java.lang.String
     * @author : cwl
     * @date : 2019/7/12 17:14
     */
    private static void setIdfield(Object src) throws NoSuchFieldException, IllegalAccessException {
        Class<?> srcClass = src.getClass();
        Field srcId = srcClass.getDeclaredField(FIELD_NAME_ID);
        srcId.setAccessible(true);
        srcId.set(src,getID());
    }

    /**
     * 功能描述:
     * 〈获取32位ID〉
     *
     * @params : []
     * @return : java.lang.String
     * @author : cwl
     * @date : 2019/10/17 14:26
     */
    public static String getID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 功能描述:
     * 〈当id为空时,设置它id的值.常见于编辑时使用〉
     *
     * @params : [list]
     * @return : void
     * @author : cwl
     * @date : 2019/7/2 9:38
     */
    public static Map<String,Integer> setId(List<? extends Object> list, Long lastId) throws Exception {
        Long longId = lastId;
        Map<String,Integer> sortAndIdMap = new HashMap<>();
        for (int i=0;i<list.size();i++) {
            Object instance = list.get(i);
            Class<?> clazz = instance.getClass();
            Field id = clazz.getDeclaredField(FIELD_NAME_ID);
            id.setAccessible(true);
            if(isEmpty(id.get(instance))){
                if(longId != null){
                    longId++;
                    id.set(instance,longId);
                }else{
                    id.set(instance, getID());
                }
            }

            sortAndIdMap.put(id.get(instance).toString(),i);
        }
        return sortAndIdMap;
    }

    /**
     * 功能描述:
     * 〈获取ID集合〉
     *
     * @params : [list]
     * @return : java.util.List<java.lang.String>
     * @author : cwl
     * @date : 2019/10/17 14:31
     */
    private static <T> List<String> getIdList(List<T> list) throws NoSuchFieldException, IllegalAccessException {
        List<String> resultList = new ArrayList<>();
        for (T src : list) {
            resultList.add(getIdfield(src));
        }
        return resultList;
    }

    /**
     * 功能描述:
     * 〈根据反射获得对象ID值〉
     *
     * @params : [src]
     * @return : java.lang.String
     * @author : cwl
     * @date : 2019/7/2 10:29
     */
    private static <T> String getIdfield(T src) throws NoSuchFieldException, IllegalAccessException {
        Class<?> srcClass = src.getClass();
        Field srcId = srcClass.getDeclaredField(FIELD_NAME_ID);
        srcId.setAccessible(true);
        return srcId.get(src).toString();
    }

    /**
     * 功能描述:
     * 〈获取ID-PO的Map集合〉
     *
     * @params : [srcList]
     * @return : java.util.Map<java.lang.String,java.lang.Object>
     * @author : cwl
     * @date : 2019/7/2 10:36
     */
    private static <T> Map<String, T> getPOMap(List<T> list) throws NoSuchFieldException, IllegalAccessException {
        Map<String, T> resultMap = new HashMap<>();
        for(T src : list){
            resultMap.put(getIdfield(src),src);
        }
        return resultMap;
    }
}
